import axios from 'axios'

let BASE_API = '/api';

axios.defaults.headers.common['Authorization'] = localStorage.getItem('token')

export default {
	/**
	 * post 请求
	 * @param url
	 * @param params
	 * @returns {Promise<any>}
	 * @constructor
	 */
	POST: (url, params) => {
		return new Promise((resolve, reject) => {
			axios.post(BASE_API + url, params).then((response) => {
				resolve(response.data);
			}).catch((err) => {
				reject(err);
			});
		});
	},

	/**
	 * get 请求
	 * @param url
	 * @param params
	 * @returns {Promise<any>}
	 * @constructor
	 */
	GET: (url, params) => {
		return new Promise((resolve, reject) => {
			if (params && params.needEncodeUri) {
				let paramsCopy = JSON.parse(JSON.stringify(params));
				delete paramsCopy.needEncodeUri;
				let paramsStr = '';
				for (let key in paramsCopy) {
					paramsStr += key + '=' + paramsCopy[key] + '&';
				}
				paramsStr = paramsStr.substring(0, paramsStr.length - 1);
				let serviceURL = BASE_API + url + '?' + paramsStr;
				axios({
					method: 'get',
					url: encodeURI(serviceURL),
				}).then((response) => {
					resolve(response.data);
				}).catch((err) => {
					reject(err);
				});
			} else {
				axios.get(BASE_API + url, {
					params
				}).then((response) => {
					resolve(response.data);
				}).catch((err) => {
					reject(err);
				});
			}

		});
	},

	/**
	 * DELETE请求
	 * @param url
	 * @param params
	 * @returns {Promise<unknown>}
	 * @constructor
	 */
	DELETE: (url, params) => {
		return new Promise((resolve, reject) => {
			axios.delete(BASE_API + url, params).then((response) => {
				resolve(response);
			}).catch((err) => {
				reject(err);
			});
		});
	},

	/**
	 * PUT 请求
	 * @param url
	 * @param params
	 * @returns {Promise<unknown>}
	 * @constructor
	 */
	PUT: (url, params) => {
		return new Promise((resolve, reject) => {
			if (params && params.needEncodeUri) {
				let paramsCopy = JSON.parse(JSON.stringify(params));
				delete paramsCopy.needEncodeUri;
				let paramsStr = '';
				for (let key in paramsCopy) {
					paramsStr += key + '=' + paramsCopy[key] + '&';
				}
				paramsStr = paramsStr.substring(0, paramsStr.length - 1);
				let serviceURL = BASE_API + url + '?' + paramsStr;
				axios({
					method: 'put',
					url: encodeURI(serviceURL),
				}).then((response) => {
					resolve(response);
				}).catch((err) => {
					reject(err);
				});
			} else {
				axios.put(BASE_API + url, params).then((response) => {
					resolve(response);
				}).catch((err) => {
					reject(err);
				});
			}

		});
	}
};